package com.lz.wsy.controller;

import com.lz.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Api(tags = "图片上传接口")
@RestController
@RequestMapping("/file")
public class ImgeUploadController {


    @ApiOperation(value = "单个文件上传",notes = "单个文件上传")
    @RequestMapping(value = "singlefile",method= RequestMethod.POST)
    public Result uploadImge(MultipartFile file, HttpServletRequest request) {
        try{

            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!path.exists()) path = new File("");
            //如果上传目录为/static/images/upload/，则可以如下获取：
            //在开发测试模式时，得到的地址为：{项目跟目录}/target/static/images/upload/
            //在打包成jar正式发布时，得到的地址为：{发布jar包目录}/static/images/upload/
            File staticPath = new File(path.getAbsolutePath(),"static/images/upload/");
            if(!staticPath.exists()) staticPath.mkdirs();

            //获取文件名
            long time = new Date().getTime();
            //时间戳+图片名
            String fileName = time+file.getOriginalFilename();

            //图片存储目录以及图片名称
            String urlPath = "images" + File.separator + fileName;
            //图片保存路径
            String savePath = staticPath + File.separator + urlPath;
            System.out.println("图片保存地址：" + savePath);
            // 访问路径=静态资源路径+文件目录路径
            String visitPath = "static/" + urlPath;

            //图片访问路径存数据库
            String devNamePaht = "/images/upload/images/"+fileName;
            System.out.println("图片访问uri：" + devNamePaht);

            request.setAttribute("devNamePaht",devNamePaht);
            File saveFile = new File(savePath);
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }
            try {
                file.transferTo(saveFile);  //将临时存储的文件移动到真实存储路径下
            } catch (IOException e) {
                e.printStackTrace();
            }
            return Result.success(devNamePaht);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }




}
